package com.ruoyi.web.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.exception.ResultException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@Controller
public class CommonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 文件上传路径
     */
    public static final String UPLOAD_PATH = "/profile/upload/";

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = Global.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.uploadFileRename(filePath, file);
            String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传图片
     */
    @RequestMapping("common/uploadImage")
    @ResponseBody
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file, String type) throws ResultException {
        if (file.isEmpty()) {
            return AjaxResult.error("上传图片不能为空");
        }
        String filePath = uploadImageToFTPComp(file, "/images/" +
                (StringUtils.isNotEmpty(type) ? type + "/" : ""), 1000);
        return AjaxResult.success().put("filePath", filePath);
    }

    /**
     * 上传多张图片
     */
    @RequestMapping("common/uploadImageList")
    @ResponseBody
    public AjaxResult uploadImageList(@RequestParam("file") MultipartFile file, String type) throws Exception {
        if (file.isEmpty()) {
            return AjaxResult.error("上传图片不能为空");
        }

        String originalName = file.getOriginalFilename();
        String name = originalName.substring(0,originalName.indexOf("."));
        String suffix = originalName.substring(originalName.lastIndexOf(".") + 1);
        if (!"jpg".equalsIgnoreCase(suffix) && !"jpeg".equalsIgnoreCase(suffix) && !"png".equalsIgnoreCase(suffix)
                &&!"gif".equalsIgnoreCase(suffix)) {
            throw new Exception("请上传jpeg/jpg/png文件");
        }

        String filePath = uploadImageToFTPComp(file, "/images/" +
                (StringUtils.isNotEmpty(type) ? type + "/" : ""), 1000);
        return AjaxResult.success().put("filePath", filePath).put("imgId", name);
    }


    /**
     * 上传文件
     */
    @RequestMapping("common/uploadFile")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, String type) throws ResultException {
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }
        String filePath = uploadFileToFTP(file, "/files/" +
                (StringUtils.isNotEmpty(type) ? type + "/" : ""));
        return AjaxResult.success().put("filePath", filePath);
    }
}
